package com.zhanggm.springcloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证服务是否完成，也就是用户是否登录了
 * 如果没有登录，我们不让它请求后端服务
 */
//@Component
public class AuthFilter extends ZuulFilter {
    /**
     * 过滤类型
     * 设置在路由转发之前进行过滤
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器的时候，可以设置过滤顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        System.out.println("shouldFilter");
        //获得request对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String requestURI = request.getRequestURI();
        //放行用户部分请求
        if(requestURI.startsWith("/api/user")){
            return false;
        }
        return true;
    }

    /**
     * 具体的过滤逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("run");
        //获得request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        //验证用户是否登录
        String token = request.getParameter("token");
        //如果是空说明没有登录
        //验证token是否合法，也就是是否登录的时候生成token，是否过期
        if(StringUtils.isEmpty(token)){
            //表示不进行路由,不会被zuul转发到后端服务器
            currentContext.setSendZuulResponse(false);
            //http状态码，标识未授权
            currentContext.setResponseStatusCode(403);
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write("{\"code\":10000,\"msg\":\"未授权\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
